import { SysFiles } from '../tables/SysFiles';

import { fileUrl } from '../url';
import { PsdResult, doLogin } from '../request1';

// 选择照片并上传
export function ChooseUploadFile(options : { mask ?: boolean, preview ?: (path : string) => void, success : (file : SysFiles) => void }) {
	uni.chooseImage({
		count: 1,
		sizeType: ['original', 'compressed'], // 指定选择的图片类型，可以选择原图和压缩图，这里设置为二者都有
		sourceType: ['album', 'camera'], // 指定选择图片的来源，这里设置为相册和相机
		success: (res) => {
			if (options.preview != undefined) {
				options.preview(res.tempFilePaths[0]);
			}
			uploadFile({
				...options,
				filePath: res.tempFilePaths[0],
				fail: (code : any, message : string) => {
					console.log('code:%d,message:%s', code, message);
					uni.showModal({ content: `上传图片失败，错误提示${message}`, showCancel: false });
				},
			});
		},
	});
}
export function uploadFile(options : { filePath : string, mask ?: boolean, success : (result : SysFiles) => void, fail : (code : number, message ?: string) => void }) {
	const Logintoken = uni.getStorageSync('Logintoken');
	if (Logintoken !== '') {
		if (options.mask != undefined && options.mask) {
			uni.showLoading({ mask: true });
		}
		uni.uploadFile({
			url: fileUrl,
			fileType: 'image',
			name: 'file', // 上传的file的名称
			filePath: options.filePath, // 上传的单文件内容File对象
			header: { Logintoken },
			success: (res) => {
				if (options.mask != undefined && options.mask) {
					uni.hideLoading();
				}
				const result = JSON.parse(res.data) as PsdResult<SysFiles>;
				if (result.code === 4000 || result.code === 4001) {
					uni.removeStorageSync('Logintoken');
					uni.removeStorageSync('phone');
					uploadFile(options);
				} else if (result.code == 200 || result.code == 2000) {
					options.success(result.content as SysFiles);
				} else {
					options.fail(result.code, result?.message);
				}
			},
			fail: (err) => {
				if (options.mask != undefined && options.mask) {
					uni.hideLoading();
				}
				if (options?.fail) {
					console.log(err)
					options.fail(1, JSON.stringify(err));
				}
			},
		});
	} else {
		doLogin({
			success: (Logintoken : string, phone : string) => {
				uni.setStorageSync('Logintoken', Logintoken);
				uni.setStorageSync('phone', phone);
				uni.uploadFile({
					url: fileUrl,
					name: 'file', // 上传的file的名称
					filePath: options.filePath, // 上传的单文件内容File对象
					header: { Logintoken },
					success: (res) => {
						const result = JSON.parse(res.data) as PsdResult<SysFiles>;
						if (result.code == 200) {
							options.success(result.content as SysFiles);
						} else {
							options.fail(result.code, result?.message);
						}
					},
					fail: (err) => {
						options.fail(1, JSON.stringify(err));
					},
				});
			},
			fail: options.fail,
		});
	}
}
